<template>
  <view class="leave-application">
    <!-- 表单内容 -->
    <view class="form-box">
      <!-- 请假类型 -->
      <view class="form-item form-item-picker required" v-if="type == 'askForLeave'">
        <text class="label">Leave Category</text>
        <!-- <picker class="picker" mode="selector" :range="categoryList" @change="onCategoryChange"> -->
        <view class="picker">
          <view class="picker-inner" @click="showCategoryPickerqj">
            <text class="picker-content">
              <img class="pickerIcon" src="/static//image/calendar.png" style="
                  position: relative;
                  bottom: -8rpx;
                  width: 38rpx;
                  padding-right: 10rpx;
                " alt="" />
              <text>{{ selectedCategory.label || "Select Category" }}</text>
            </text>
            <uv-icon name="arrow-down" color="#47C28B" size="19"></uv-icon>
          </view>
        </view>
        <!-- </picker> -->
      </view>
      <!-- 请假类型 -->
      <view class="form-item form-item-picker required">
        <text class="label">{{
          type == "askForLeave" ? "Leave Duration" : "Replacement date"
        }}</text>
        <!-- <picker class="picker" mode="selector" :range="categoryList" @change="onCategoryChange"> -->
        <view class="picker" @click="
          () => {
            (calendarsType = ''), $refs.calendars.open();
          }
        ">
          <view class="picker-inner">
            <text class="picker-content">
              <img class="pickerIcon" src="/static//image/calendar.png" style="
                  position: relative;
                  bottom: -8rpx;
                  width: 38rpx;
                  padding-right: 10rpx;
                " alt="" />
              <text>{{ selecteTime || "Select Duration" }}</text>
            </text>
            <uv-icon name="arrow-down" color="#47C28B" size="19"></uv-icon>
          </view>
        </view>
        <!-- </picker> -->
      </view>

      <!-- 时长/天数 -->
      <view class="form-item required" v-if="type == 'askForLeave'">
        <text class="label">Duration/days</text>
        <!-- <uv-input class="input" placeholder="According to the selection of display time" border="surround" v-model="day"></uv-input> -->
        <input @blur="handleDays" type="number" class="input" v-model="day" style="width: auto"
          placeholder="According to the selection of display time" />
      </view>

      <!-- 请假类型 -->
      <view class="form-item form-item-picker required" v-if="type != 'askForLeave'">
        <text class="label">Replacement timecard type</text>
        <view class="picker" @click="showCategoryPicker">
          <view class="picker-inner">
            <text class="picker-content">
              <img class="pickerIcon" src="/static//image/calendar.png" style="
                  position: relative;
                  bottom: -8rpx;
                  width: 38rpx;
                  padding-right: 10rpx;
                " alt="" />
              <text>{{
                (selectedCategory && selectedCategory.text) || "Forget to punch in"
              }}</text>
            </text>
            <uv-icon name="arrow-down" color="#47C28B" size="19"></uv-icon>
          </view>
        </view>
      </view>

      <!-- 请假时间 -->
      <!-- <view class="form-item form-item-picker required">
                <text class="label">请假时间</text>
                <picker class="picker" mode="date" @change="onDateChange">
                    <view class="picker-inner">
                        <text class="picker-content ">
                            <img class="pickerIcon" src="/static//image/calendar.png"
                                style="position: relative;bottom: -8rpx;width: 38rpx;padding-right: 10rpx;" alt="">
                            <text>{{ selectedCategory || '请选择类型' }}</text>
                        </text>
                        <uv-icon name="arrow-down" color="#47C28B" size="19"></uv-icon>
                    </view>
                </picker>
            </view> -->

      <!-- 时长/天数 -->
      <!-- <view class="form-item required" @click="() => { calendarsType= 'range', $refs.calendars.open() }">
                <text class="label">Duration/days</text>
                <input class="input" style="width: auto;" placeholder="According to the selection of display time" />
            </view> -->

      <uv-calendars ref="calendars" :selected="list" :date="selecteTime" :mode="calendarsType"
        :disable="type == 'cardReplacement'" color="#17A364" @confirm="confirm" />

      <!-- 请假事由 -->
      <view class="form-item">
        <text class="label">{{
          type == "askForLeave"
            ? "Leave Description"
            : "Reason for replacement card"
        }}</text>
        <textarea class="textarea" v-model="content" style="width: auto" :placeholder="type == 'askForLeave'
          ? 'Enter Leave Description'
          : 'Enter the reason for replacing the card'
          " />
      </view>

      <!-- 图片上传 -->
      <view class="form-item required">
        <text class="label">Picture <text class="tip">Upload a maximum of 9 images</text></text>
        <uv-upload action="/api/common/upload" @afterRead="handleAfterRead" :fileList="fileList" name="3" multiple
          :maxCount="9" :previewFullImage="true" @delete="handleDelete">
          <div class="uploadIcon">
            <uv-icon name="plus"></uv-icon>
          </div>
        </uv-upload>
      </view>
      <!-- <view class="form-item required">
                <text class="label">图片 <text class="tip">最多上传9张</text></text>
                <view class="img-list">
                    <view v-for="(img, idx) in images" :key="idx" class="img-item">
                        <image :src="img" mode="aspectFill" />
                    </view>
                    <view v-if="images.length < 9" class="img-upload" @tap="chooseImage">
                        <uv-icon name="plus" size="20"></uv-icon>

                    </view>
                </view>
            </view> -->

      <!-- 审批人 -->
      <view class="form-item required" style="margin-top: 30rpx">
        <text class="label">Examine and approve</text>
        <!-- <view class="approver-add" @tap="addApprover">
                    <uv-icon name="plus" size="20"></uv-icon>
                </view> -->
        <view class="approver-list">
          <uv-steps current="-1" inactiveColor="#A2E0C4" dot direction="column">
            <uv-steps-item v-for="(item, index) in stepsList" :desc="item.state ? 'In approval' : 'Pending approval'" :key="index">
              <template v-slot:title>
                <view class="stepsName">
                  <text style="margin-right: 5px">{{ item.username }}</text>
                  <!-- <uv-icon name="close" color="#fff"></uv-icon> -->
                </view>
              </template>
            </uv-steps-item>
          </uv-steps>
          <view v-for="(person, idx) in approvers" :key="idx" class="approver-item">
            <text>{{ person }}</text>
          </view>
        </view>
      </view>
      <uv-popup ref="popup" @change="change">
        <view style="width: 350rpx; height: calc(100vh - 88rpx); overflow-y: scroll">
          <uv-list>
            <uv-list-item v-for="(item, index) in 50" :key="index" :title="`列表${index}`"
              thumb="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/460d46d0-4fcc-11eb-8ff1-d5dcf8779628.png"
              thumb-size="lg">
            </uv-list-item>
            <!-- <uv-list-item :show-extra-icon="true" :extra-icon="{icon:'photo',color:'red'}" title="列表左侧带扩展图标">
                        </uv-list-item> -->
          </uv-list>
        </view>
      </uv-popup>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-btns">
      <button class="btn save" @tap="onSubmit(1)">Save for release</button>
      <button class="btn submit" @tap="onSave(0)">Submit</button>
    </view>

    <uv-popup ref="showphoneModal" round="20" @change="changePopup" :customStyle="{ overflow: 'initial' }">
      <view class="forgot-modal" v-if="submitState == 1">
        <view class="modal-icon-box">
          <uv-icon class="modal-icon" size="56" color="#fff" name="lock-fill"></uv-icon>
        </view>
        <view class="modal-title">Submit Leave</view>
        <view class="modal-tip">
          Double-check your leave details to ensure everything is correct. Do
          you want to proceed?
        </view>
        <button class="forgot-btn" @click="onSubmit(0)">Yes, Submit</button>
        <button class="cancel-btn" @click="
          () => {
            forgotPwdStatus = 2;
          }
        ">
          No, Let me check
        </button>
      </view>
      <view class="forgot-modal" v-if="submitState == 2">
        <view class="modal-icon-box">
          <uv-icon class="modal-icon" size="56" color="#fff" name="lock-fill"></uv-icon>
        </view>
        <view class="modal-title">Leave Submitted!</view>
        <view class="modal-tip">
          Your leave request has been sent for review! Wait for HR to review
          your request.
        </view>
        <button class="forgot-btn" @click="handlelLogList">
          View Expense History
        </button>
      </view>
    </uv-popup>

    <uv-popup ref="showCategory" :title="['Leave Category', 'Select Leave category']" round="20"
      :customStyle="{ overflow: 'initial' }">
      <view class="category-popup">
        <view class="category-container">
          <view class="category-options">
            <view v-for="(option, index) in categoryList" :key="index" class="category-option" :class="{
              'category-option-selected': selectedCategory === option,
            }" @click="selectAndConfirmCategory(option)">
              <view class="category-option-text">
                <view class="name">{{ option.label }}</view>
                <view>{{ option.text }}</view>
              </view>
            </view>
          </view>
          <view class="category-actions">
            <view class="category-close-btn" @click="closeCategoryPicker">
              Close
            </view>
          </view>
        </view>
      </view>
    </uv-popup>
    <!-- 请假类型 -->
    <uv-popup ref="showCategoryqj" :title="['Leave Category', 'Select Leave category']" round="20"
      :customStyle="{ overflow: 'initial' }">
      <view class="category-popup">
        <view class="category-container">
          <view class="category-options">
            <view v-for="(option, index) in categoryList" :key="index" class="category-option" :class="{
              'category-option-selected':
                selectedCategory.value == option.value,
            }" @click="selectAndConfirmCategoryqj(option)">
              <view class="category-option-text">{{ option.label }}</view>
            </view>
          </view>
          <view class="category-actions">
            <view class="category-close-btn" @click="closeCategoryPicker">
              Close
            </view>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js'
import {
  replacementList,
  replacementClock,
  getAttendanceLogDetail,
  getAttendanceRule,
  getErrorAttendance,
} from "@/api/attendace.js";
import {
  getLeaveCategory,
  leaveApply,
  replacementDetail,
  getAuditUser
} from "@/api/replacement";
import { uploadFile } from "@/api/home";
export default {
  data() {
    return {
      categoryList: [
        {
          name: "上班迟到 （9：50）",
          text: "应该9：00上班",
        },
      ],
      statusColor: {
        1: "#19B36E",
        2: "#19B36E",
        3: "#F79009",
        4: "#195EB3",
        5: "#19B36E",
        6: "#F95555"
      },
      selectedCategory: {},
      calendarsType: "",
      content: "",
      type: "askForLeave",
      result: {},
      selecteTime: "",
      selectedDate: "",
      submitState: 1,
      images: [],
      fileList: [],

      stepsList: [
        { name: "和主管1", id: 0, state: 0 },
        { name: "和主管2", id: 1, state: 0 },
      ],
      approvers: [],
      list: [],
    };
  },
  async onLoad({ id, type, day }) {
    this.id = id || '';
    this.type = type;
    let approvalLists =  await getAuditUser({ id: id })
    this.stepsList = approvalLists.map(ele => {
      return { name: ele.name, id: ele.id, state: 0,...ele.user_info }
    })
    console.log(approvalLists, 'approvalLists');
    if (id) {
      replacementDetail({ id: id }).then((res) => {
        let approvalList = [res.user];
        this.type = res.type == 1 ? "cardReplacement" : "askForLeave";
        this.content = res.data.content
        this.selecteTime = dayjs(res.date).format("YYYY-MM-DD");
        this.fileList = res.data.images.map(item => ({ url: item }));
        this.confirm({ fulldate: this.selecteTime });
        if (res.audit_user) {
          approvalList.push(res.audit_user);
        }
        if (res.audit_user1) {
          approvalList.push(res.audit_user1);
        }
        this.detail = {
          ...res,
          approvalList,
        };
      });
    }
    if(day){
      this.selecteTime =  dayjs(day).format("YYYY-MM-DD");
      console.log(this.selecteTime);
      this.confirm({ fulldate: this.selecteTime });
    }
    uni.setNavigationBarTitle({
      title: type == "askForLeave" ? 'Leave application' : 'Timecard replacement application'
    })
    if(type == "cardReplacement") return;
    getLeaveCategory({}).then((res) => {
      this.categoryList = res;
      this.selectedCategory = (res && res[0]) || {};
      if (this.categoryList.length == 1) {
        this.selectedCategory = this.categoryList[0];
      }
    });
  },
  created() {
    this.getlist();
    this.range = uni.$uv.date(new Date().getTime(), "YYYY-MM-DD");
    // this.showCategoryPicker()
  },
  methods: {
    async getlist() {
      let list = await replacementList({});
      this.list = list.map((ele) => {
        return {
          ...ele,
          badge: true,
          date: ele.label,
          disable: false,
          infoColor: this.statusColor[ele.status] || "#F79009",
        };
      });

      console.log("confirm", this.list);
    },
    async confirm(e) {
      this.selecteTime = e.fulldate;
      if (this.type == "cardReplacement") {
        let categoryList = [];
        let list = await getErrorAttendance({ date: e.fulldate });
        console.log(' ', list)
        list.map((ele) => {
          if (ele.status == 3 || ele.status == 6) {
            categoryList.push({
              ...ele,
              text: `应${ele.rule_timestamp}${ele.rule_id == 1 ? "上班" : "下班"
                }`,
              label: `${ele.rule_id == 1 ? "上班" : "下班"}${ele.status == 3 ? "缺卡" : "迟到"
                }（${ele.rule_timestamp}）`,
            });
          }
        });
        this.categoryList = categoryList;
        if (this.selectedCategory && !this.selectedCategory.rule_id) {
          this.selectedCategory = this.categoryList[0];
        }
      }
    },
    onCategoryChange(e) {
      this.selectedCategory = this.categoryList[e.detail.value];
    },
    onDateChange(e) {
      this.selectedDate = e.detail.value;
    },
    async handleAfterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      const result = await uploadFile(event.file[0].url);
      this.fileList.push({
        url: result.full_path,
      });
    },
    handleDelete(a) {
      this.fileList.splice(a.index, 1);
      console.log("handleDelete", a, this.fileList);
    },
    addApprover() {
      // 添加审批人逻辑
      this.$refs.popup.open("right");
    },
    showCategoryPicker() {
      if (this.categoryList.length == 1) {
        this.selectedCategory = this.categoryList[0];
      }
      this.$refs.showCategory.open("bottom");
    },
    showCategoryPickerqj() {
      this.$refs.showCategoryqj.open("bottom");
    },
    selectAndConfirmCategory(category) {
      this.selectedCategory = category;
      this.$refs.showCategory.close();
    },
    selectAndConfirmCategoryqj(category) {
      this.selectedCategory = category;
      this.$refs.showCategoryqj.close();
    },
    onSave() {
      // 保存草稿逻辑
      if (this.type == "cardReplacement" && !this.selecteTime) {
        return uni.$uv.toast("Please select the date to be replaced");
      }

      if (this.type == "cardReplacement" && !this.selectedCategory?.text) {
        return uni.$uv.toast("Replacement timecard type");
      }
      console.log("this.fileList", this.content);
      if (!this.content) {
        return uni.$uv.toast(
          this.type == "askForLeave"
            ? "Enter Leave Description"
            : "Enter the reason for replacing the card"
        );
      }

      if (this.fileList.length == 0) {
        return uni.$uv.toast("Replacement timecard type");
      }

      uni.$uv.toast("正在提交");
      this.$refs.showphoneModal.open("bottom");
    },
    async onSubmit(only_save = 0) {
      // 提交逻辑
      let that = this;
      this.submitState = 1;
      // 提交逻辑
      if (this.type == "cardReplacement") {
        //补卡
        that.result = await replacementClock({
          id: this.id,
          attendance_id: this.selectedCategory.attendance_id,
          rule_id: this.selectedCategory.rule_id,
          content: this.content,
          images: this.fileList.map((ele) => ele.url).join(","),
          only_save,
        });
      } else {
        if (!this.day) {
          return uni.$uv.toast("According to the selection of display time");
        }
        that.result = await leaveApply({
          id: this.id,
          days: this.day,
          start_time: dayjs(this.range).format("YYYY-MM-DD"),
          end_time: dayjs(this.range).add(this.day, "day").format("YYYY-MM-DD"),
          content: this.content,
          images: this.fileList.map((ele) => ele.url).join(","),
          category: this.selectedCategory.value,
          only_save,
        });
      }
      that.submitState = 2;
      // this.$refs.showphoneModal.open('bottom')
    },
    handlelLogList() {
      uni.$uv.route({ type: "tab", url: "/pages/Approval/approval" })
    },
    changePopup({ show }) {
      let that = this;
      if (show) return;
      if (this.submitState === 2) {
        uni.$uv.route({
          url: "/pages/Approval/approvalDetail",
          params: {
            id: that.result.id,
          },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.leave-application {
  background: #f8f9fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 56px;
  background: #fff;
  padding: 0 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);

  .back-btn {
    font-size: 22px;
    margin-right: 16px;
  }

  .title {
    font-size: 20px;
    font-weight: bold;
  }
}

.uploadIcon {
  width: 80px;
  height: 80px;
  border: 1px dashed #dcdfe6;
  background: #fafbfc;
  text-align: center;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.img-upload {
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.form-box {
  background: #fff;
  border-radius: 12px;
  margin: 15px 12px;
  padding: 23px 15px;
  flex: 1;

  .form-item {
    margin-bottom: 18px;

    .label {
      font-size: 15px;
      color: #333;
      margin-bottom: 6px;
      display: block;
    }

    .tip {
      color: #f56c6c;
      font-size: 12px;
      margin-left: 8px;
    }

    .picker,
    .input,
    .textarea {
      width: 100%;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      padding: 10px;
      font-size: 15px;
      background: #f7f8fa;
      margin-top: 6px;
    }

    .picker-inner {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .iconfont {
      font-size: 14px;
      color: #bbb;
    }

    .img-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 8px;

      .img-item,
      .img-upload {
        width: 64px;
        height: 64px;
        border: 1px dashed #dcdfe6;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fafbfc;
      }

      .img-item image {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }

      .plus {
        font-size: 32px;
        color: #bbb;
      }
    }

    .approver-add {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fafbfc;
      border-radius: 50%;
      border: 1px solid #98a2b3;

      .plus {
        font-size: 40rpx;
        color: #bbb;
      }
    }

    .approver-list {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 8px;

      .stepsName {
        background: #17a364;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 10px 10px 10px 10px;
        color: #fff;
        padding: 8px 15px;
      }

      .approver-item {
        background: #e6f7ff;
        color: #1890ff;
        border-radius: 50%;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
      }
    }
  }

  .required .label:before {
    content: "* ";
    color: #f56c6c;
  }
}

.category-container {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
  padding-bottom: 30rpx;
}

.category-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f2f2f2;
  text-align: center;
}

.category-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.category-options {
  padding: 0 23px 10rpx 23px;
  margin-bottom: 20rpx;
}

.category-option {
  display: flex;
  align-items: center;
  padding: 34rpx 24rpx;
  position: relative;
  transition: background-color 0.2s;
  margin-bottom: 8px;
  box-shadow: 0px 1 2px 0px rgba(16, 24, 40, 0.05);
  border-radius: 8px 8px 8px 8px;
  border: 1px solid #98a2b3;
}

.category-option:active {
  background-color: #f9f9f9;
}

.category-option-selected {
  border: 1px solid #19b36e;
  background-color: rgba(25, 179, 110, 0.1);
}

.category-option-selected::after {
  content: "";
  position: absolute;
  right: 30rpx;
  width: 36rpx;
  height: 36rpx;
  background-color: #19b36e;
  border-radius: 50%;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z'/%3E%3C/svg%3E");
  background-size: 24rpx;
  background-position: center;
  background-repeat: no-repeat;
}

.category-option-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(25, 179, 110, 0.1);
  margin-right: 20rpx;
}

.category-option-icon image {
  width: 40rpx;
  height: 40rpx;
}

.category-option-text {
  font-size: 24rpx;
  line-height: 38rpx;
  color: #333;
  flex: 1;

  .name {
    font-size: 26rpx;
  }
}

.category-actions {
  padding: 20rpx 30rpx;
}

.category-close-btn {
  margin: 0 30rpx;
  border: 1rpx solid #19b36e;
  color: #19b36e;
  font-size: 32rpx;
  font-weight: 500;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  text-align: center;
}

.category-submit-btn {
  display: none;
}
</style>